<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch">
            <el-form-item label="操作人" prop="userName">
                <el-input v-model="queryParams.userName" placeholder="请输入操作人" clearable style="width: 200px;" />
            </el-form-item>
            <el-form-item label="请求时间" prop="time">
                <el-date-picker v-model="dateRangeTime" type="datetimerange" range-separator="-"
                    start-placeholder="开始日期" end-placeholder="结束日期" placeholder="请选择触发时间"
                    value-format="YYYY-MM-DD HH:mm:ss" :default-time="defaultTime" clearable>
                </el-date-picker>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
                <el-button icon="refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="danger" plain icon="delete" :disabled="multiple" @click="handleDelete"
                    v-hasFunc="'operation:del'">删除</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="danger" plain icon="delete" @click="handleClearAll"
                    v-hasFunc="'operation:del'">一键清空</el-button>
            </el-col>
            <right-toolbar :showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="dataList" @selection-change="handleSelectionChange" highlight-current-row
            @row-dblclick="handleView">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="主键" align="center" prop="id" :show-overflow-tooltip="true"
                v-if="columns.showColumn('id')">
                <template #default="scope">
                    {{ scope.row.id }}
                </template>
            </el-table-column>
            <el-table-column label="追踪ID" align="center" prop="traceIdentifier" :show-overflow-tooltip="true"
                v-if="columns.showColumn('traceIdentifier')">
                <template #default="scope">
                    {{ scope.row.traceIdentifier }}
                </template>
            </el-table-column>
            <el-table-column label="请求时间" align="center" prop="requestTime" :show-overflow-tooltip="true"
                v-if="columns.showColumn('requestTime')" width="180">
                <template #default="scope">
                    {{ parseTime(scope.row.requestTime) }}
                </template>
            </el-table-column>
            <el-table-column label="响应时间" align="center" prop="responseTime" :show-overflow-tooltip="true"
                v-if="columns.showColumn('responseTime')" width="180">
                <template #default="scope">
                    {{ parseTime(scope.row.responseTime) }}
                </template>
            </el-table-column>
            <el-table-column label="耗时(ms)" align="center" prop="duration" :show-overflow-tooltip="true"
                v-if="columns.showColumn('duration')" width="80">
                <template #default="scope">
                    {{ scope.row.duration }}
                </template>
            </el-table-column>
            <el-table-column label="请求方法" align="center" prop="httpMethod" :show-overflow-tooltip="true"
                v-if="columns.showColumn('httpMethod')">
                <template #default="scope">
                    {{ scope.row.httpMethod }}
                </template>
            </el-table-column>
            <el-table-column label="请求地址" align="center" prop="url" :show-overflow-tooltip="true"
                v-if="columns.showColumn('url')">
                <template #default="scope">
                    {{ scope.row.url }}
                </template>
            </el-table-column>
            <el-table-column label="客户端地址" align="center" prop="address" :show-overflow-tooltip="true"
                v-if="columns.showColumn('address')">
                <template #default="scope">
                    {{ scope.row.address }}
                </template>
            </el-table-column>
            <el-table-column label="客户端IP" align="center" prop="clientIP" :show-overflow-tooltip="true"
                v-if="columns.showColumn('clientIP')">
                <template #default="scope">
                    {{ scope.row.clientIP }}
                </template>
            </el-table-column>
            <el-table-column label="操作人" align="center" prop="userName" :show-overflow-tooltip="true"
                v-if="columns.showColumn('userName')">
                <template #default="scope">
                    {{ scope.row.userName }}
                </template>
            </el-table-column>
            <el-table-column label="操作人ID" align="center" prop="userId" :show-overflow-tooltip="true"
                v-if="columns.showColumn('userId')">
                <template #default="scope">
                    {{ scope.row.userId }}
                </template>
            </el-table-column>
            <el-table-column label="代理信息" align="center" prop="userAgent" :show-overflow-tooltip="true"
                v-if="columns.showColumn('userAgent')">
                <template #default="scope">
                    {{ scope.row.userAgent }}
                </template>
            </el-table-column>
            <el-table-column label="关联接口id" align="center" prop="endpointId" :show-overflow-tooltip="true"
                v-if="columns.showColumn('endpointId')">
                <template #default="scope">
                    {{ scope.row.endpointId }}
                </template>
            </el-table-column>
            <el-table-column label="接口名称" align="center" prop="actionName" :show-overflow-tooltip="true"
                v-if="columns.showColumn('actionName')">
                <template #default="scope">
                    {{ scope.row.actionName }}
                </template>
            </el-table-column>

            <el-table-column label="操作" align="center" width="160">
                <template #default="scope">
                    <el-button type="primary" text icon="delete" @click="handleDelete(scope.row)"
                        v-hasFunc="'operation:del'">删除</el-button>
                    <el-button type="primary" text icon="view" @click="handleView(scope.row)"
                        v-hasFunc="'operation:info'">查看</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageIndex"
            v-model:limit="queryParams.pageSize" @pagination="getList" />

        <!-- 添加或修改对话框 -->
        <el-drawer :title="title" v-model="open" width="500px" header-class="drawer-header">
            <el-descriptions title="基本信息" :column="1" border label-width="80px" style="margin-bottom: 30px;">
                <el-descriptions-item label="主键"> {{ form.id }} </el-descriptions-item>
                <el-descriptions-item label="追踪ID"> {{ form.traceIdentifier }} </el-descriptions-item>
                <el-descriptions-item label="请求时间"> {{ parseTime(form.requestTime) }} </el-descriptions-item>
                <el-descriptions-item label="响应时间"> {{ parseTime(form.responseTime) }} </el-descriptions-item>
                <el-descriptions-item label="耗时(ms)"> {{ form.duration }} </el-descriptions-item>
                <el-descriptions-item label="请求方法"> {{ form.httpMethod }} </el-descriptions-item>
                <el-descriptions-item label="请求地址"> {{ form.url }} </el-descriptions-item>
                <el-descriptions-item label="客户端地址"> {{ form.address }} </el-descriptions-item>
                <el-descriptions-item label="客户端IP"> {{ form.clientIP }} </el-descriptions-item>
                <el-descriptions-item label="操作人"> {{ form.userName }} </el-descriptions-item>
                <el-descriptions-item label="操作人ID"> {{ form.userId }} </el-descriptions-item>
                <el-descriptions-item label="代理信息"> {{ form.userAgent }} </el-descriptions-item>
                <el-descriptions-item label="接口名称"> {{ form.actionName }} </el-descriptions-item>

            </el-descriptions>
            <el-collapse :model-value="['arguments', 'responseBody']">
                <el-collapse-item title="请求参数" name="arguments">
                    <codemirror v-model="form.arguments" :autofocus="true" :indent-with-tab="true" :tab-size="2"
                        :extensions="extensions" @blur="log('blur', $event)" :style="{ maxHeight: '80vh' }" />
                    <div style="text-align: right;">
                        <!-- <el-button type="primary" size="default" link @click="" icon="DocumentCopy">
                            复制
                        </el-button> -->
                    </div>
                </el-collapse-item>
                <el-collapse-item title="响应数据" name="responseBody">
                    <codemirror v-model="form.responseBody" :autofocus="true" :indent-with-tab="true" :tab-size="2"
                        :extensions="extensions" @blur="log('blur', $event)" :style="{ maxHeight: '80vh' }" />
                    <div style="text-align: right;">
                        <!-- <el-button type="primary" size="default" link @click="" icon="DocumentCopy">
                            复制
                        </el-button> -->
                    </div>
                </el-collapse-item>
            </el-collapse>
        </el-drawer>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { listRequestTrackingLog, getRequestTrackingLog, delRequestTrackingLog, addRequestTrackingLog, updateRequestTrackingLog, clearRequestTrackingLog } from "@/api/log/requesttrackinglog.js";
import { Codemirror } from 'vue-codemirror'
import { json } from '@codemirror/lang-json'
import { oneDark } from '@codemirror/theme-one-dark'

const lang = ref("json")
const extensions = [json(), oneDark]

const { proxy } = getCurrentInstance()


//弹窗操作类型
//0:新增，1：修改，2:查看
const operateType = ref(0)
//表单ref
const formRef = ref();
// 遮罩层
const loading = ref(true);
// 选中数组
const selected = ref([]);
// 显示搜索条件
const showSearch = ref(true);
// 总条数
const total = ref(0);
// 数据集
const dataList = ref([]);
// 弹出层标题
const title = ref("");
// 是否显示弹出层
const open = ref(false);

//默认时间范围
const defaultTime = ref([new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 59)])
//定义触发时间查询参数
const dateRangeTime = ref([]);
// 查询参数
const queryParams = reactive({
    pageIndex: 1,
    pageSize: 10,
    sort: "RequestTime"
});



const state = reactive({
    single: true,
    multiple: true,
    form: {

    },
    rules: {
        //customerId: [{ required: true, message: "客户id不能为空", trigger: "blur"    , type: "number"  }],
        //name: [{ required: true, message: "商品名称不能为空", trigger: "blur"     }],
    },
    options: {
        // 商品种类 选项列表 格式 eg:{ dictLabel: '标签', dictValue: '0'}
        typeOptions: [],
    }
})

const { form, rules, options, single, multiple } = toRefs(state)


//所有列
const columns = ref([
    { visible: false, prop: 'id', label: '主键' },
    { visible: true, prop: 'traceIdentifier', label: '追踪ID' },
    { visible: true, prop: 'requestTime', label: '请求时间' },
    { visible: true, prop: 'responseTime', label: '响应时间' },
    { visible: true, prop: 'duration', label: '耗时(ms)' },
    { visible: true, prop: 'httpMethod', label: '请求方法' },
    { visible: true, prop: 'url', label: '请求地址' },
    { visible: false, prop: 'address', label: '客户端地址' },
    { visible: true, prop: 'clientIP', label: '客户端IP' },
    { visible: true, prop: 'userName', label: '操作人' },
    { visible: false, prop: 'userId', label: '操作人ID' },
    { visible: false, prop: 'userAgent', label: '代理信息' },
    { visible: false, prop: 'endpointId', label: '关联接口id' },
    { visible: true, prop: 'actionName', label: '接口名称' }
]);

// 获取列表方法
const getList = () => {
    loading.value = true;
    proxy.addDateRange(queryParams, dateRangeTime.value, 'RequestTime');
    listRequestTrackingLog(queryParams).then((response) => {
        dataList.value = response.result;
        total.value = response.totalNum;
        loading.value = false;
    });
};

// 重置表单
const reset = () => {

};

// 搜索按钮操作
const handleQuery = () => {
    queryParams.pageIndex = 1;
    getList();
};

// 重置按钮操作
const resetQuery = () => {
    dateRangeTime.value = [];
    proxy.resetForm("queryRef");
    reset();
    handleQuery();
};

// 多选框选中数据
const handleSelectionChange = (selection) => {
    selected.value = selection.map((item) => item.id);
    single.value = selection.length !== 1;
    multiple.value = !selection.length;
};

// 新增按钮操作
const handleAdd = () => {
    reset();
    operateType.value = 0;
    open.value = true;
    title.value = "添加数据";
};


//查看
const handleView = (row) => {
    reset();
    operateType.value = 2;
    var key = row.id;
    getRequestTrackingLog(key).then((response) => {
        Object.assign(form.value, response);
        open.value = true;
        title.value = "查看明细";
    });
}

// 提交按钮
const submitForm = () => {
    const validateForm = formRef.value?.validate;
    if (validateForm) {
        validateForm((valid) => {
            if (valid) {
                const apiCall = form.value.id ? updateRequestTrackingLog : addRequestTrackingLog;
                apiCall(form.value).then(() => {
                    proxy.$modal.msgSuccess("操作成功");
                    open.value = false;
                    getList();
                });
            }
        });
    }
};

//取消弹窗
const cancel = () => {
    open.value = false;
    proxy.resetForm("form")
}

// 删除按钮操作
const handleDelete = (row) => {
    const keys = [].concat(row.id || selected.value);
    proxy.$modal.confirm("是否确认删除编号为" + keys + "的数据项？")
        .then(() => delRequestTrackingLog(keys))
        .then(() => {
            getList();
            proxy.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
};

//一键清空
const handleClearAll = () => {
    proxy.$modal.confirm("是否确认清空所有 操作记录 数据？")
        .then(() => clearRequestTrackingLog())
        .then(() => {
            getList();
            proxy.$modal.msgSuccess("清空成功");
        })
        .catch(() => { });
}

// 导出按钮操作
const handleExport = () => {
    download("system//export", queryParams, `menu_${new Date().getTime()}.xlsx`);
};

// 页面加载时调用获取列表方法
onMounted(getList);
</script>


<style lang="scss" scoped>
:deep(.drawer-header) {
    margin: 0;
}

:deep(.trace-desc) {
    word-break: break-word;
}
</style>
